//
//  ViewController.m
//  SocketRocketDemo
//
//  Created by lz on 2018/12/6.
//  Copyright © 2018 lz. All rights reserved.
//

#import "ViewController.h"
#import "WebSocketManager.h"

@interface ViewController () <WebSocketManagerDelegate, UITextViewDelegate, UITextFieldDelegate>

@property (nonatomic, strong) UITextView *textView;

@property (nonatomic, strong) WebSocketManager *webSocketManager;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    
    self.textView = [[UITextView alloc]initWithFrame:CGRectMake(0, 20, CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame) *0.5)];
    self.textView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    self.textView.delegate = self;
    self.textView.editable = NO;
    [self.view addSubview:self.textView];
    
    UITextField *textField = [[UITextField alloc]init];
    textField.frame = CGRectMake(0, self.textView.frame.origin.y + self.textView.frame.size.height +10, CGRectGetWidth(self.textView.frame) , 30);
    textField.borderStyle = UITextBorderStyleRoundedRect;
    textField.placeholder = @"请输入内容";
    textField.delegate = self;
    textField.returnKeyType = UIReturnKeySend;
    textField.enablesReturnKeyAutomatically = YES;
    [self.view addSubview:textField];
    
    
    UIButton *disconnectBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [disconnectBtn setTitle:@"断开连接" forState:UIControlStateNormal];
    [disconnectBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    disconnectBtn.backgroundColor = [UIColor redColor];
    disconnectBtn.frame = CGRectMake(20, textField.frame.origin.y + textField.frame.size.height + 10, 80, 30);
    [disconnectBtn addTarget:self action:@selector(disconnectBtnAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:disconnectBtn];
    
    
    //单例创建
    //[LZWebSocketManager lz_connectSocketWithUrl:@"ws://echo.websocket.org" delegate:self];
    //手动创建
    [self.webSocketManager lz_connect];
    
}


#pragma mark - Action

- (void)disconnectBtnAction {
//    [LZWebSocketManager lz_disconnect];
    [self.webSocketManager lz_disconnect];
    //可以直接释放
//    _webSocketManager = nil;
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
//    [LZWebSocketManager lz_sendMessage:textField.text];
    [self.webSocketManager lz_sendMessage:textField.text];
    textField.text = nil;
    return YES;
}

#pragma mark - UITextViewDelegate

- (void)textViewDidChange:(UITextView *)textView {
    
}


#pragma mark - WebSocketManagerDelegate
/**
 已经连接
 
 @param socket WebSocketManager
 */
- (void)lz_webSocketDidConnect:(WebSocketManager *)socket {
    NSLog(@"连接成功");
    //TODO
    //可以发送登录信息。。。
}

/**
 已经断开连接
 
 @param socket WebSocketManager
 */
- (void)lz_webSocketDidDisconnect:(WebSocketManager *)socket {
    NSLog(@"已经断开连接");
}

/**
 连接失败
 
 @param socket WebSocketManager
 */
- (void)lz_webSocketConnectError:(WebSocketManager *)socket {
    NSLog(@"失败");
    //TODO
}

/**
 已经收到消息
 
 @param socket WebSocketManager
 @param data 数据
 */
- (void)lz_webSocket:(WebSocketManager *)socket didReceiveMessage:(id)data {
    NSLog(@"\n---->%@",data);
    //TODO
    if ([data isKindOfClass:[NSString class]]) {
        NSString *receiveMessage = [NSString stringWithFormat:@"\n-->%@",data];
        self.textView.text = [self.textView.text stringByAppendingString:receiveMessage];
    }
}

/**
 消息发送失败
 
 @param socket WebSocketManager
 @param socketStatus Socket的连接状态
 */
- (void)lz_webSocket:(WebSocketManager *)socket sendMessageError:(LZWebSocketStatus)socketStatus {
    if (!socket) return;
    switch (socketStatus) {
        case LZWebSocketStatusNotConnected:
        {
            [self alertWithReconnect];

            //如果WebSocketManager被释放、此处应该手动连接
//            [socket lz_connect:@"ws://echo.websocket.org"];
            //如果没有释放，可以继续使用重连方法
            [socket lz_reconnect];
            //或者直接连接的方法
//            [socket lz_connect];
        }
            break;
        case LZWebSocketStatusFailed:
        {
            NSLog(@"发送失败\n正在与服务器建立连接...");
        }
            break;
        case LZWebSocketStatusClosedByServer:
        case LZWebSocketStatusClosedByUser:
        {
            [self alertWithReconnect];
        }
            break;
        default:
            break;
    }
}

//手动重连提示
- (void)alertWithReconnect {
    UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"WebSocketManager与服务器断开连接\n是否尝试重新连接？" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *connectAction = [UIAlertAction actionWithTitle:@"重新连接" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
//        [LZWebSocketManager lz_reconnect];
        [self.webSocketManager lz_reconnect];
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
//        [LZWebSocketManager lz_disconnect];
        [self.webSocketManager lz_disconnect];
    }];
    [alert addAction:connectAction];
    [alert addAction:cancelAction];
    dispatch_async(dispatch_get_main_queue(), ^{
        [self presentViewController:alert animated:YES completion:nil];
    });
}


#pragma mark - Lazy load.

- (WebSocketManager *)webSocketManager {
    if (!_webSocketManager) {
        _webSocketManager = [[WebSocketManager alloc]init];
        _webSocketManager.delegate = self;
        _webSocketManager.urlString = @"ws://echo.websocket.org";
    }
    return _webSocketManager;
}

@end
